package com.itcs.app.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.itcs.app.model.Message;
import com.itcs.app.service.AccountService;
import com.itcs.app.util.Codes;
import com.itcs.box.common.util.IDCardUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 账户Controller
 * 
 * @author LiuPeng
 * @date 2017年12月15日
 * 
 */
@Api(value = "账户controller", tags = { "账户操作接口" })
@RestController
@RequestMapping("/account")
public class AccountController {
	private static Logger logger = LoggerFactory.getLogger(AccountController.class);

	@Autowired
	private AccountService accountService;

	/**
	 * 绑定银行卡 操作表名： user_bank_info,user_customer_info
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation("绑定银行卡")
	@PostMapping("/addBankCard")
	@ResponseBody
	public Message addBankCard(@RequestParam(name="userId",defaultValue="1",required=true) Long userId,
			@RequestParam(name = "authName", defaultValue = "abc", required = true)String authName,
			@RequestParam(name = "icCard", defaultValue = "123", required = true) String icCard,
			@RequestParam(name = "mobile", defaultValue = "133，默认为用户注册手机号,不允许修改", required = true) String mobile,
			@RequestParam(name = "cardNo", defaultValue = "123", required = true) String cardNo,
			@RequestParam(name = "cardType", defaultValue = "1", required = true) Integer cardType,
			HttpServletRequest request, HttpServletResponse response
			) {
		// 校验上送报文
		// 校验身份证是否合法
		if (!IDCardUtil.isIdentity(icCard)) {
			return new Message(300, "不是有效的身份证号码");
		}

		if (!IDCardUtil.mobile(mobile)) {
			return new Message(300, "不是有效的手机号码");
		}

		// 调用ping++，获取银行卡信息
		/* 请求认证接口
		 * 请求参数  type:REQUIRED,身份证信息或者银行卡信息串，取值范围: "id_card"（身份证信息串）；"bank_card"（银行卡信息串）
		 * 		 app:REQUIRED,
		 * 		 data:REQUIRED  
		 * 						id_name:REQUIRED,string,身份证姓名(1~16位)。
								id_number:REQUIRED,string,身份证号码(15位或18位)。
								card_number:REQUIRED,string,银行卡号(12～19位)，仅在  type 参数为 "bank_card" 时必传， type 参数为 "id_card" 时请勿传此参数。
								phone_number:optional/string,手机号(11位)，仅在  type 参数为 "bank_card" 时可以选择是否传此参数，暂不支持178开头的手机号。 type 参数为 "id_card" 时请勿传此参数。
		 */
		
		/*身份证银行卡信息认证接口
		 * type:String,身份证信息或者银行卡信息串，取值范围:"id_card"（身份证信息串）；"bank_card"（银行卡信息串）
		 * app:String,appId
		 * result_code:int,返回码，0		成功
								1001	签名验证失败
								1002	参数格式不正确
								2001	调用第三方接口失败
								2002	操作数据库失败
								3200	无效的商户号
								3204	无效的 sessionId
								3300	商户号未找到
								3303	商户号与服务访问账号不匹配
								3420	请求参数不合法
								3431	身份证信息不匹配
								3432	身份证信息匹配失败
								3433	身份验证活体照片非法
								3434	身份验证上传登记照失败
								3435	身份验证照片比对失败
								3441	银行卡信息认证失败
								3442	银行卡信息认证请求异常
								3443	银行卡信息认证请求超时
								3451	银行卡信息认证校验失败
								3452	银行卡信息认证校验异常
		  * message:String,描述信息，接口调用失败时为错误描述，成功时为 "SUCCESS" 。
		  * paid:boolean,是否已扣款，扣款为  true ，未扣款为  false 
		  * data:map,id_name string 身份证姓名(1~16位)；
					id_number string 身份证号码(15位或18位)；
					card_number string 银行卡号(12～19位) 仅在  type 参数为 "bank_card" 的时候必需要传此参数；
					phone_number string 手机号(11位) 仅在  type 参数为 "bank_card" 的时候可以选择是否传此参数，暂不支持178开头的手机号。
								
		 	{
			   "type": "id_card",
			   "app": "app_LibTW1n1SOq9Pin1",
			   "result_code": 0,
			   "message": "SUCCESS",
			   "paid":true,
			   "data": {
			       "id_name": "张三",
			       "id_number": "320291198811110000"
			   }
			} 
		 */
		//调用ping++，暂时不实现//TODO

		// 调用service
		Map<String, Object> param = new HashMap<>();
		param.put("userId", userId);
		param.put("authName", authName);
		param.put("icCard", icCard);
		param.put("mobile", mobile);
		param.put("cardNo", cardNo);
		param.put("cardType", cardType);
		Map<String, Object> result = accountService.addBankCard(param);

		logger.info("service response:{}",result.get(Codes.CODE).toString());
		// 返回
		/**
		 * { "message": "成功", "code": 200 }
		 * 
		 * 非200的状态都是认证不通过 { "message": "", 认证状态 :不一致、验证异常 "code": 300 }
		 * 
		 */
		return new Message(Codes.SUCCESS, "成功");
	}

	/**
	 * 银行卡列表 
	 * 查询表名： user_bank_info,user_customer_info
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation("银行卡列表")
	@PostMapping("/findBankCard")
	@ResponseBody
	public String findBankCard(
			@RequestParam(name="userId",defaultValue="1",required=true) Long userId,
			HttpServletRequest request, HttpServletResponse response
			 ) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 查询数据库 user_bank_info,user_customer_info
			logger.info("userId:"+userId);
			logger.info("request:"+request.getParameter("userId"));
			List<Map<String, Object>> data = accountService.findBankCard(userId);
			// 返回
			result.put("total", data.size());
			result.put("data", data);
			result.put(Codes.CODE, Codes.SUCCESS);
		} catch (Exception e) {
			result.put(Codes.CODE, Codes.ERROR);
			e.printStackTrace();
		}
		 
		
		String json = JSON.toJSONString(result);
		return json;
		/**
		 * 
		 * 
		 * { "total": 1, "data": [ { "cardId": 120, //绑定id "userId": 3, //用户ID
		 * "authName": "", "icCard": " ", "mobile": " ", "cardNo": " ",
		 * "cardType": "" } ], "code": 200 }
		 * 
		 * 
		 */
		/*
		 * return "{\r\n" + "  \"total\": 1,\r\n" + "  \"data\": [\r\n" +
		 * "    {\r\n" + "      \"cardId\": 120,  //绑定id\r\n" +
		 * "      \"userId\": 3,     //用户ID\r\n" +
		 * "      \"authName\": \"\",\r\n" + "      \"icCard\": \" \", \r\n" +
		 * "      \"mobile\": \" \",  \r\n" + "      \"cardNo\": \" \",   \r\n"
		 * + "      \"cardType\": \"\" \r\n" + "    }\r\n" + "  ],\r\n" +
		 * "  \"code\": 200\r\n" + "}\r\n" + "";
		 */
	}

	/**
	 * 用户提现 操作表名：user_cashin_op_his TODO
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation("用户提现")
	@PostMapping("/withdrawals")
	public Message withdrawals(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(name = "userId", value = "用户id", required = true) Long id,
			@ApiParam(name = "amount", value = "提现金额", required = true) Double amount,
			@ApiParam(name = "cardId", value = "提现卡号id", required = true) String cardId) {

		// 返回
		/**
		 * 
		 * 
		 * { "message": "成功", "code": 200 }
		 * 
		 * 非200的状态都是认证不通过 { "message": "失败，原因：", "code": 300 }
		 * 
		 */
		return new Message(200, "成功");
	}

	/**
	 * 提现记录列表 查询表名：user_cashin_op_his
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation("提现记录列表")
	@PostMapping("/findWithdrawals")
	public String findWithdrawals(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(name = "userId", defaultValue = "1", required = true) Long id,
			@RequestParam(name = "pageSize", defaultValue = "1", required = true) Integer pageSize,
			@RequestParam(name = "pageIndex", defaultValue = "1", required = true) Integer pageIndex
			) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 查询数据库user_cashin_op_his
			logger.info("account controller received:id-{},pageSize-{},pageIndex-{}",id, pageSize, pageIndex);
			List<Map<String, Object>> data = accountService.findWithdrawals(id, pageSize, pageIndex);
			// 返回
			result.put("total", data.size());
			result.put("data", data);
			result.put("code", 200);
		} catch (Exception e) {
			result.put("code", 300);
			e.printStackTrace();
		}
		String json = JSON.toJSONString(result);
		return json;

		// 返回
		/**
		 * 
		 * 
		 * { "total": 1, "data": [ { "cardId": 120, //绑定id "userId": 3, //用户ID
		 * "authName": "", "icCard": " ", "mobile": " ", "cardNo": " ",
		 * "cardType": ""
		 * 
		 * "status": "" 处理状态 "created": "" 申请日期 } ], "code": 200 }
		 * 
		 * 
		 */
		/*
		 * return "{\r\n" + "  \"total\": 1,\r\n" + "  \"data\": [\r\n" +
		 * "    {\r\n" + "      \"cardId\": 120,  //绑定id\r\n" +
		 * "      \"userId\": 3,     //用户ID\r\n" +
		 * "      \"authName\": \"\",\r\n" + "      \"icCard\": \" \", \r\n" +
		 * "      \"mobile\": \" \",  \r\n" + "      \"cardNo\": \" \",   \r\n"
		 * + "      \"cardType\": \"\" \r\n" + "\r\n" +
		 * "      \"status\": \"\" 处理状态\r\n" +
		 * "      \"created\": \"\" 申请日期\r\n" + "    }\r\n" + "  ],\r\n" +
		 * "  \"code\": 200\r\n" + "}\r\n" + "";
		 */
	}

	/**
	 * 用户资金 
	 * 查询表名：user_account_info
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation("用户资金")
	@PostMapping("/wallet")
	public String wallet(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(name = "userId", defaultValue = "1", required = true) Long id) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 查询数据库user_account_info,user_customer_info
			List<Map<String, Object>> data = accountService.wallet(id);
			// 返回
			result.put("total", data.size());
			result.put("data", data);
			result.put("code", 200);
		} catch (Exception e) {
			result.put("code", 300);
			e.printStackTrace();
		}
		String json = JSON.toJSONString(result);
		return json;
		
		// 返回
		/**
		 * 
		 * { "total": 1, "data": [ { "userId": 3, //用户ID "amount": "", "lv": " "
		 * , //用户等级 "totalX": " ",//用户积分 } ], "code": 200 }
		 * 
		 */
		/*return "{\r\n" + "  \"total\": 1,\r\n" + "  \"data\": [\r\n" + "    {\r\n"
				+ "      \"userId\": 3,     //用户ID\r\n" + "      \"amount\": \"\",\r\n"
				+ "      \"lv\": \" \",  //用户等级\r\n" + "      \"totalX\": \" \",//用户积分   \r\n" + "		账户资金信息\r\n"
				+ "    }\r\n" + "  ],\r\n" + "  \"code\": 200\r\n" + "}\r\n" + "";*/
	}

	public static void main(String[] args) {
		BigDecimal num1 = new BigDecimal("50");
		BigDecimal num2 = new BigDecimal("50");
		BigDecimal result2 = num1.subtract(num2);

		System.out.println("差    是   :  " + result2);
		
		System.out.println(num1.compareTo(num2));
	}

}
